package com.job2e.common.utils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;

/**
 * Common utility methods for whole website.
 * @author Laiss
 *
 */
public class CommonUtil {
	private static Calendar cal=Calendar.getInstance();
	
	/**
	 * 日期增加天数
	 * @param dt
	 * @param days
	 * @return
	 */
	public static Date addDay(Date dt, int days) {
		cal.setTime(dt);
		cal.add(Calendar.DATE, days);
		return cal.getTime();
	}
	
	/**
	 * 日期增加分钟数
	 * @param dt
	 * @param minutes
	 * @return
	 */
	public static Date addMinute(Date dt, int minutes) {
		cal.setTime(dt);
		cal.add(Calendar.MINUTE, minutes);
		return cal.getTime();
	}
	
	/**
	 * 字符串转为日期
	 * @param dateString
	 * @param format
	 * @return
	 */
	public static Date getDateFormString(String dateString, String format) {
		try {
			DateFormat df = new SimpleDateFormat(format);
			return df.parse(dateString);
		}
		catch (ParseException e) {
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 * 日期转为字符串
	 * @param date
	 * @param format
	 * @return
	 */
	public static String toDateFormString(Date date, String format) {
		DateFormat df = new SimpleDateFormat(format);
		return df.format(date);
	}
	
	// 获取格式化的日期显示，如今天 08:95
	public static String getFormattedDateString(Date date) {
	    if (date == null) {
	        return "";
	    }
		Date currentDate = new Date();
		cal.setTime(currentDate);
		cal.clear(Calendar.HOUR_OF_DAY);
		cal.clear(Calendar.MINUTE);
		cal.clear(Calendar.SECOND);
		cal.clear(Calendar.MILLISECOND);
		
		Calendar calReal = Calendar.getInstance();
		calReal.setTime(date);
		int hours = calReal.get(Calendar.HOUR_OF_DAY);
		int minutes = calReal.get(Calendar.MINUTE);
		
		if (calReal.getTimeInMillis() > cal.getTimeInMillis()) {
			return "今天 " + hours + ":" + (minutes < 10 ? "0" + minutes : minutes);
		}
		
		if (calReal.getTimeInMillis() > (cal.getTimeInMillis() - 24 * 3600000)) {
			return "昨天 " + hours + ":" + (minutes < 10 ? "0" + minutes : minutes);
		}
		
		if (calReal.getTimeInMillis() > (cal.getTimeInMillis() - 48 * 3600000)) {
			return "前天 " + hours + ":" + (minutes < 10 ? "0" + minutes : minutes);
		}
		return toDateFormString(date, "MM月dd日 HH时mm分");
	}
	
	public static String getSortedString(List<String> strList, String separator) {
		if (strList == null) {
			return null;
		}
		Collections.sort(strList);
		StringBuffer sb = new StringBuffer();
		for (String str : strList) {
			sb.append(separator).append(str);
		}
		if (sb.length() > 0) {
			sb.delete(0, separator.length());
		}
		return sb.toString();
	}
	
	public static void copyFile(InputStream is, String dstFile) throws FileNotFoundException, IOException{
		final int maxLen = 10240;
		byte[] buff = new byte[maxLen];
		int len = 0;
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(new File(dstFile));
			do {
				len = is.read(buff);
				if (len > 0) {
					fos.write(buff, 0, len);
				}
			}
			while (len > 0);
		} finally {
	        try {
	            fos.close();
	        } catch (IOException ignored) {
	        }
	    }
	}
	
	public static void copyFile(InputStream is, OutputStream os) throws FileNotFoundException, IOException{
		final int maxLen = 10240;
		byte[] buff = new byte[maxLen];
		int len = 0;
		do {
			len = is.read(buff);
			if (len > 0) {
				os.write(buff, 0, len);
			}
		}
		while (len > 0);
	}
	
	// create a list by a map, it's unordered. 
	public static <T> List<T> convertToList(Map<Long, T> srcMap) {
		if (srcMap == null) {
			return null;
		}
		List<T> list = new ArrayList<T>();
		for (T value : srcMap.values()) {
			list.add(value);
		}
		return list;
	}
	
	// create a list by a map, it's ordered well by given IDs.
	public static <T> List<T> convertToList(Map<Long, T> srcMap, List<Long> idList) {
		if (srcMap == null || idList == null) {
			return null;
		}
		List<T> list = new ArrayList<T>();
		for (Long key : idList) {
			list.add(srcMap.get(key));
		}
		return list;
	}
	
	/**
	 * 根据请求信息返回用户的ip
	 * @param request
	 * @return
	 */
	public static String getIpAddress(HttpServletRequest request) {
		String ip = request.getHeader("X-Real-IP");
        if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
        	ip = request.getHeader("x-forwarded-for");
        }
        if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
	}
	
	public interface ReplaceDisposer {
		String dispose(String str);
	}
	
	/**
	 * 替换
	 * @param source
	 * @param pattern
	 * @param disposer
	 * @return
	 */
	public static String replaceByRegex(String source, String pattern,
			ReplaceDisposer disposer) {
		Pattern p = Pattern.compile(pattern);
		// 用Pattern类的matcher()方法生成一个Matcher对象
		Matcher m = p.matcher(source);
		StringBuffer sb = new StringBuffer();
		while (m.find()) {
			String str = disposer.dispose(m.toString());
			m.appendReplacement(sb, str);
		}
		// 最后调用appendTail()方法将最后一次匹配后的剩余字符串加到sb里；
		m.appendTail(sb);
		return sb.toString();
	}
	
	/**
	 * 是否匹配
	 * @param source
	 * @param pattern
	 * @return
	 */
	public static boolean isMatch(String source, String pattern) {
		Pattern p = Pattern.compile(pattern);
		Matcher m = p.matcher(source);
		return m.find();
	}
	
	/**
	 * 匹配，没找到返回-1
	 * @param source
	 * @param pattern
	 * @return
	 */
	public static int match(String source, String pattern) {
		Pattern p = Pattern.compile(pattern);
		Matcher m = p.matcher(source);
		if (m.find()) {
			return m.start();
		}
		return -1;
	}
}
